<?php

class SiteController extends AdminController
{
  public $defaultAction = 'login';

  public function init()
  {
    Yii::app()->user->loginUrl = '/admin/site/login';
  }

  public function filters()
  {
    return array(
        'accessControl', // perform access control for CRUD operations
            //'postOnly + delete', // we only allow deletion via POST request
    );
  }

  public function accessRules()
  {
    return array(
        array('allow', // allow all users to access 'index' and 'view' actions.
            'actions' => array('login'),
            'users' => array('*'),
        ),
        array('allow',
            'actions' => array('index', 'logout'),
            'roles' => array('member'),
        ),
        array('deny',
            'users' => array('*'),
        ),
    );
  }

  /**
   * This is the default 'index' action that is invoked
   * when an action is not explicitly requested by users.
   */
  public function actionIndex()
  {
    $this->render('index');
  }

  /**
   * This is the action to handle external exceptions.
   */
  public function actionError()
  {
    if ($error = Yii::app()->errorHandler->error) {
      if (Yii::app()->request->isAjaxRequest)
        echo $error['message'];
      else
        $this->render('error', $error);
    }
  }

  /**
   * Displays the login page
   */
  public function actionLogin()
  {
    if(!Yii::app()->user->isGuest) {//check login

      $this->redirect('/admin/users/list');
    }

    $model = new LoginForm;

    // if it is ajax validation request
    if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
      echo CActiveForm::validate($model);
      Yii::app()->end();
    }

    // collect user input data
    if (isset($_POST['LoginForm'])) {
      $model->attributes = $_POST['LoginForm'];
      // validate user input and redirect to the previous page if valid
      if ($model->validate() && $model->login()) {
          
          if (Constants::isAdmin()) {
            $this->redirect(array('/admin/members/list'));
          } else {
            $this->redirect(array('/admin/accountTracking/list'));
          } 
      }
    }

    // display the login form
    $this->renderPartial('login', array('model' => $model));
  }

  /**
   * Logs out the current user and redirect to homepage.
   */
  public function actionLogout()
  {
    Yii::app()->user->logout();
    $this->redirect(Yii::app()->user->loginUrl);
  }

  public function actionTestAjax()
  {
    echo CJSON::encode(array('status' => 1, 'message' => 'ok'));
  }

}